function extractPptxText(pptxFile) {
    return new Promise(async (resolve, reject) => {
        try {
            const zip = await JSZip.loadAsync(pptxFile);
            const slides = zip.folder('ppt/slides');
            
            // 验证文件结构
            if (!slides) {
                throw new Error('Invalid PPTX format: missing slides directory');
            }

            // 收集并排序幻灯片文件
            const slideFiles = [];
            slides.forEach((relativePath, file) => {
                if (!file.dir) {
                    const slideNum = parseInt(relativePath.match(/slide(\d+)\.xml$/i)?.[1], 10);
                    if (slideNum) slideFiles.push({ slideNum, file });
                }
            });

            slideFiles.sort((a, b) => a.slideNum - b.slideNum);

            // 处理每张幻灯片
            const result = [null]; // 索引 0 占位
            for (const { slideNum, file } of slideFiles) {
                try {
                    const xml = await file.async('text');
                    const doc = new DOMParser().parseFromString(xml, 'text/xml');
                    
                    // 提取所有文本节点（兼容不同命名空间）
                    const texts = Array.from(doc.querySelectorAll('a\\:t, t'))
                                    .map(t => t.textContent.trim())
                                    .filter(Boolean)
                                    .join(' ');
                    
                    result[slideNum] = texts;
                } catch (e) {
                    console.warn(`Slide ${slideNum} processing failed:`, e);
                    result[slideNum] = ''; // 保留占位
                }
            }

            resolve(result);
        } catch (e) {
            reject(e);
        }
    });
}


async function checkTokenApi(backend_domain_name, token){
    const formData = new URLSearchParams();
    formData.append('token', token);

    try {
        const response = await fetch(backend_domain_name + '/pptx_generates_questions/check_token', {
            method: 'POST',
            body: formData,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            }
        })
        const data = await response.json();

        if (data.TF == 'T'){
            return data.username;
            // 验证成功要将用户名展示在页面上
        } else {
            console.log(data.message)
            // 验证失败要访问 front_end_domain_name + '/login_register_page'
            return null;
        }
    } catch {
        // 验证失败要访问 front_end_domain_name + '/login_register_page'
        return null;
    }
} 

async function getQuestionsByPptxTextApi(backend_domain_name, token, pptxText, userPrompt){
    const formData = new URLSearchParams();
    formData.append('token', token);
    formData.append('texts', pptxText); // Pptx 文件的所有文本
    formData.append('user_request', userPrompt); // 用户要求，可为空

    try {
        const response = await fetch(
            backend_domain_name + '/pptx_generates_questions/get_questions_by_pptx_text',
            {
                method: 'POST',
                body: formData,
            }
        )
        const data = await response.json();
        if (data.TF == 'T'){
            if (data.ai_output == 'AI 接口调用失败'){
                return {'TF': false, 'message': data.ai_output};
            }
            console.log(data.ai_output);
            return {
                'TF': true, 
                'ai_output': data.ai_output // 可能为 Markdown 格式, 页面需要适配这种格式进行展示
            };
        } else {
            console.log(data.message);
            return {'TF': false, 'message': data.message};
        }
    } catch (error) {
        console.log(error);
        return {'TF': false, 'message': '网络错误'};
    }
}

async function getQuestionsAnswersByQuestionsAndPptxTextApi(
    backend_domain_name, token, questions, pptxText
){
    const formData = new URLSearchParams();
    formData.append('token', token);
    formData.append('questions', questions);
    formData.append('pptx_texts', pptxText);
    try{
        const response = await fetch(
            backend_domain_name + '/pptx_generates_questions/get_questions_answers_by_pptx_text',
            {
                method: 'POST',
                body: formData,
            }
        )
        const data = await response.json();
        if (data.TF == 'T'){
            console.log(data.ai_output);
            return {
                "TF": true,
                "ai_output": data.ai_output // 可能为 Markdown 格式, 页面需要适配这种格式进行展示
            }
        } else {
            console.log(data.message);
            return {'TF': false, 'message': data.message};
        }
    } catch (error) {
        console.log(error);
        return {'TF': false, 'message': '网络错误'};
    }
}